import React, { Component } from "react";
import { DatePicker, Popconfirm, Button, message, Spin, Select, Form, Icon } from "antd"
import moment from "moment";
import { inspectPlanRecoverApi, pushRecoverApi, recoverLastTermInspectPlanMakeApi } from "../js/dataRecover.js"
import { getAllMunicipalityApi } from "../js/api.js"
import { getSchoolLevelByEduIdApi } from "../js/edudailystatistics.js";
const { RangePicker } = DatePicker;
class InspectPlanRecover extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: "",
            loading: false
        }
    }
    componentDidMount() {

    }

    disabledDate(current) {
        return current > moment().endOf('day');
    }

    dateChange(date, dateString) {
        this.setState({
            date: dateString
        })
    }

    dayConfirm(e) {
        if (this.state.date == undefined || this.state.date == "") {
            message.warning("请选择日期")
        } else {
            this.setState({
                loading: true
            })
            inspectPlanRecoverApi(this.state.date, "日").then((res) => {
                if (res.data == "success") {
                    message.success("恢复成功！")
                    this.setState({
                        loading: false
                    })
                } else {
                    message.error("恢复失败！")
                }
            }).catch((err) => {
                console.log(err);
                message.error("恢复失败！")
            })
        }
    }

    weekConfirm(e) {
        if (this.state.date == undefined || this.state.date == "") {
            message.warning("请选择日期")
        } else {
            this.setState({
                loading: true
            })
            inspectPlanRecoverApi(this.state.date, "周").then((res) => {
                if (res.data == "success") {
                    message.success("恢复成功！")
                    this.setState({
                        loading: false
                    })
                } else {
                    message.error("恢复失败！")
                }
            }).catch((err) => {
                console.log(err);
                message.error("恢复失败！")
            })
        }
    }



    render() {
        return (
            <div style={{ position: 'relative' }}>
                {this.state.loading ? <Spin tip="Loading..." style={{ position: "absolute", left: "50%", top: "50%" }}></Spin> : null}
                <div class="timeSelect" style={{ marginTop: "100px", fontSize: "18px", textAlign: "center" }}>
                    请选择要恢复的日期：
                    <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledDate} onChange={this.dateChange.bind(this)} />
                </div>
                <div style={{ margin: "100px 300px 100px 300px", display: "flex" }}>
                    <div style={{ flex: 1, textAlign: "center" }}>
                        <Popconfirm onConfirm={this.dayConfirm.bind(this)} title="确定恢复巡检计划吗？" okText="Yes" cancelText="No">
                            <Button type="primary" style={{ height: 40 }}>巡检日计划恢复</Button>
                        </Popconfirm>
                    </div>
                    <div style={{ flex: 1, textAlign: "center" }}>
                        <Popconfirm onConfirm={this.weekConfirm.bind(this)} title="确定恢复巡检计划吗？" okText="Yes" cancelText="No">
                            <Button type="primary" style={{ height: 40 }}>巡检周计划恢复</Button>
                        </Popconfirm>
                    </div>

                </div>

            </div>
        );
    }
}

class PushRecover extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: "",
            loading: false
        }
    }
    componentDidMount() {

    }

    disabledDate(current) {
        return current > moment().endOf('day');
    }

    dateChange(date, dateString) {
        this.setState({
            date: dateString
        })
    }

    inspectPushConfirm(e) {
        if (this.state.date == undefined || this.state.date == "") {
            message.warning("请选择日期")
        } else {
            this.setState({
                loading: true
            })
            pushRecoverApi(this.state.date, 2).then((res) => {
                if (res.data == "success") {
                    message.success("恢复成功！")
                    this.setState({
                        loading: false
                    })
                } else {
                    message.error("恢复失败！")
                }
            }).catch((err) => {
                console.log(err);
                message.error("恢复失败！")
            })
        }
    }

    patrolPushConfirm(e) {
        if (this.state.date == undefined || this.state.date == "") {
            message.warning("请选择日期")
        } else {
            this.setState({
                loading: true
            })
            pushRecoverApi(this.state.date, 1).then((res) => {
                if (res.data == "success") {
                    message.success("恢复成功！")
                    this.setState({
                        loading: false
                    })
                } else {
                    message.error("恢复失败！")
                }
            }).catch((err) => {
                console.log(err);
                message.error("恢复失败！")
            })
        }
    }

    render() {
        return (
            <div style={{ position: 'relative' }}>
                {this.state.loading ? <Spin tip="Loading..." style={{ position: "absolute", left: "50%", top: "50%" }}></Spin> : null}
                <div class="timeSelect" style={{ marginTop: "100px", fontSize: "18px", textAlign: "center" }}>
                    请选择要恢复的日期：
                    <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledDate} onChange={this.dateChange.bind(this)} />
                </div>
                <div style={{ margin: "100px 300px 100px 300px", display: "flex" }}>
                    <div style={{ flex: 1, textAlign: "center" }}>
                        <Popconfirm onConfirm={this.inspectPushConfirm.bind(this)} title="确定恢复巡检推送吗？" okText="Yes" cancelText="No">
                            <Button type="primary" style={{ height: 40 }}>巡检推送恢复</Button>
                        </Popconfirm>
                    </div>
                    <div style={{ flex: 1, textAlign: "center" }}>
                        <Popconfirm onConfirm={this.patrolPushConfirm.bind(this)} title="确定恢复巡更推送吗？" okText="Yes" cancelText="No">
                            <Button type="primary" style={{ height: 40 }}>巡更推送恢复</Button>
                        </Popconfirm>
                    </div>

                </div>

            </div>
        );
    }
}


class TermInspectPlanRecover extends Component {
    constructor(props) {
        super(props);
        this.state = {
            lastTerm: [],
            nextTerm: "",
            loading: false,
            municipalityList: [],
            schoolLevel: [],
            selectedMunicipality: -1,
            selectedLevel: ""
        }
    }
    componentDidMount() {
        this.getAllMunicipality(0)
    }


    getAllMunicipality = (id) => {
        getAllMunicipalityApi(id).then((res) => {
            let municipalityList = [];
            res.data.forEach((item) => {
                let name = item.name
                name = name.slice(0, name.indexOf("直属")) + "教育局"
                municipalityList.push({
                    id: item.id,
                    name: name
                });
            });
            this.setState({
                municipalityList: municipalityList
            });
        })
    }




    selectMunicipality = (value) => {
        this.setState({
            selectedMunicipality: value
        })
        this.getSchoolLevelByEduId(value, 1)
    }


    getSchoolLevelByEduId(id, allType) {
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                let schoolLevel = []
                let finish = []
                res.data.forEach((item) => {
                    schoolLevel.push({
                        schoolLevel: item.schoolLevel
                    })
                    finish.push(false)
                })
                
                this.setState({
                    schoolLevel: schoolLevel,
                    finish: finish
                });
            })
    }



    render() {

        let municipalityOptions = []
        if (this.state.municipalityList.length != 0) {
            municipalityOptions.push(this.state.municipalityList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        let typeRow = []
        if (this.state.schoolLevel.length != 0) {
            typeRow.push(this.state.schoolLevel.map((item, index) => {
                const CreateForm = Form.create()(props => {
                    const { getFieldDecorator } = props.form;
                    const recoverConfirm = (e) => {
                        e.preventDefault()
                        if(this.state.loading == true) {
                            message.warning("正在恢复"+this.state.curType+"计划....")
                            return;
                        }
                        props.form.validateFields((err, values) => {
                            if (err) {
                                return;
                            }
                            this.setState({
                                loading: true,
                                curType: item.schoolLevel
                            })
                            const startDate = moment(values.date[0]).format("YYYY-MM-DD")
                            const endDate = moment(values.date[1]).format("YYYY-MM-DD")
                            const departmentId = this.state.selectedMunicipality
                            const schoolLevel = item.schoolLevel
                            recoverLastTermInspectPlanMakeApi(startDate, endDate, departmentId, schoolLevel).then((res) => {
                                if (res.data == "success") {
                                    message.success("恢复成功！")
                                    let finsh = this.state.finish
                                    finsh[index] = true
                                    this.setState({
                                        loading: false,
                                        finish: finsh
                                    })
                                } else {
                                    message.error("恢复失败！")
                                    this.setState({
                                        loading: false
                                    })
                                }
                            }).catch((err) => {
                                console.log(err);
                                message.error("恢复失败！")
                                this.setState({
                                    loading: false
                                })
                            })
                        })
                    }
                    return (
                        <Form style={{ marginTop: "50px", display:"flex", alignItems: "center" }} onSubmit={recoverConfirm}>
                            <span style={{ fontWeight: "bold", flex:1, textAlign:"right", paddingRight:"20px"}}>{item.schoolLevel}:</span>
                            <Form.Item style={{flex:8, margin:0}}>
                                <div style={{ display: "flex", alignItems: "center" }}>
                                    <div style={{ flex: 2 }}>
                                        {getFieldDecorator("date", {
                                            rules: [{ required: true, message: '请选择日期!' }]
                                        })(
                                            <RangePicker
                                                placeholder={['开学时间', '放假时间']}
                                                format="YYYY-MM-DD" />
                                        )}
                                        {this.state.finish[index] == true ? <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" /> : null}
                                        
                                    </div>
                                    
                                    <div style={{ flex: 1 }}>
                                        {/* <Popconfirm onConfirm={this.recoverConfirm.bind(this)} title="确定恢复上学期巡检计划吗？" okText="Yes" cancelText="No"> */}
                                        <Button htmlType="submit" type="primary">恢复上学期巡检计划</Button>
                                        {/* </Popconfirm> */}
                                    </div>
                                </div>
                            </Form.Item>
                        </Form>
                    )
                })
                return <CreateForm />
            }
            ))
        }
        return (
            <div style={{ position: 'relative' }}>
                {this.state.loading ? <Spin tip="Loading..." style={{ position: "absolute", left: "50%", top: "50%" }}></Spin> : null}
                <div>
                    <div style={{display:"flex", alignItems:"center"}}>
                        <span style={{flex:1, textAlign:"right", fontWeight:"bold", paddingRight:"20px"}}>教育局：</span>
                        <div style={{flex:8}}>
                            <Select
                                allowClear={true}
                                style={{width:"35%"}}
                                placeholder="请选择教育局"
                                onChange={this.selectMunicipality}>
                                {municipalityOptions}
                            </Select>
                        </div>
                        
                    </div>
                </div>
                {typeRow}
            </div>
        );
    }
}



export { InspectPlanRecover, PushRecover, TermInspectPlanRecover }


